package com.zte.cl.service.impl;

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.imageio.ImageIO;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import us.codecraft.webmagic.selector.Html;

import com.alibaba.fastjson.JSON;
import com.zte.cl.model.Img;
import com.zte.cl.model.News;
import com.zte.cl.model.OrigWebpage;
import com.zte.cl.parser.enums.ExtractType;
import com.zte.cl.parser.utils.ImgFull;
import com.zte.cl.parser.utils.ImgUtil;
import com.zte.cl.parser.utils.SelectableUtil;
import com.zte.cl.repository.ImgRepository;
import com.zte.cl.repository.OrigWebpageRepository;
import com.zte.cl.service.NewsService;
import com.zte.cl.service.PageContentProcessService;
import com.zte.cl.utils.ConstantUtil;
import com.zte.cl.utils.DateUtil;
import com.zte.cl.utils.RegexUtil;
import com.zte.cl.utils.SpringContextUtil;
import com.zte.cl.utils.StringUtil;
import com.zte.cl.utils.UrlUtils;

@Service("pageContentProcessServiceContentPageImpl")
public class PageContentProcessServiceContentPageImpl implements
		PageContentProcessService {

	private static final Log log = LogFactory.getLog(PageContentProcessServiceContentPageImpl.class);
	
	@Resource
	private NewsService newsService;
	
	@Resource
	private OrigWebpageRepository origWebpageRepository;
	
	@Override
	@Transactional(rollbackFor = {Exception.class})
	public void processContent(News news, Html origHtml) {
		if (news == null || StringUtil.isEmpty(news.getContent())) {
			log.error("没有获取到文章内容，请检查模板," + JSON.toJSONString(news));
			return;
		}
		
		String fileFullPath="";
		List<Img> imgList = new ArrayList<Img>();
		// 内容中是否含有图片
		if (RegexUtil.hasImg(news.getContent())) {
			// src中的相对路径，替换成http://url路径
			// 如：src="../../image.jpg" 替换成 src="http://url/image.jpg"
			String content = UrlUtils.fixAllRelativeImgSrcs(news.getContent(), news.getPageUrl());
			// 提取src路径
			List<String> orgImgList = SelectableUtil.getSelector(ExtractType.regex.toString(), RegexUtil.IMG_SRC_REGEXP).selectList(
					content);
			if (orgImgList != null && orgImgList.size() > 0) {
				Map<String, String> imgMap = new HashMap<String, String>();
				for (String rawSrc : orgImgList) {
					 ImgFull imgFull = ImgUtil.getNewImgSrc(ImgUtil.getImgFilePath(news.getChannelId()), rawSrc);
					if (imgFull != null && !StringUtil.isEmpty(imgFull.getNewSrc())) {
						if(ConstantUtil.IMG_COMPRESS){
							//等比压缩图片
							fileFullPath = ConstantUtil.IMG_PATH + imgFull.getFilePath();
							ImgUtil.scaleRatio(fileFullPath, fileFullPath, ConstantUtil.IMG_MAX_WIDTH);
						}
						imgMap.put(rawSrc, imgFull.getNewSrc());
						imgList.add(ImgUtil.getImg(news.getId(), rawSrc, imgFull.getNewSrc(), imgFull.getFilePath()));
					}
				}
				// 替换src
				if (!imgMap.isEmpty()) {
					for (String key : imgMap.keySet()) {
						content = content.replace(key, imgMap.get(key));
					}
					news.setContent(content);
				}
			}
		}
		// 文章缩略图
		if (!StringUtil.isEmpty(news.getThumbnail())) {
			String thumbnail = UrlUtils.canonicalizeUrl(news.getThumbnail(), news.getPageUrl());
			ImgFull imgFull = ImgUtil.getNewImgSrc(ImgUtil.getImgFilePath(news.getChannelId()), thumbnail);
			if (imgFull != null && !StringUtil.isEmpty(imgFull.getNewSrc())) {
				if (ConstantUtil.IMG_THUMBNAIL_COMPRESS) {
					// 等比压缩图片
					fileFullPath = ConstantUtil.IMG_PATH + imgFull.getFilePath();
					ImgUtil.scaleRatio(fileFullPath, fileFullPath, ConstantUtil.IMG_THUMBNAIL_MAX_WIDTH);
				}
				imgList.add(ImgUtil.getImg(news.getId(), thumbnail, imgFull.getNewSrc(), imgFull.getFilePath()));
				news.setThumbnail(imgFull.getNewSrc());
			}
		}else if (imgList.size() > 0) {
			String fileNamePath = null;
			boolean bScaleRatio = true;
			for (Img img : imgList) {
				bScaleRatio = true;
				// 从文章中选择一张作为缩略图
				try {
					BufferedImage srcImg = ImageIO.read(new File(ConstantUtil.IMG_PATH + img.getPath())); // 读入文件
					int width = srcImg.getWidth(); // 得到源图宽
					int height = srcImg.getHeight(); // 得到源图长
					if (width >= ConstantUtil.IMG_THUMBNAIL_MIN_WIDTH
							|| height >= ConstantUtil.IMG_THUMBNAIL_MIN_HEIGHT) {
						// 长宽大于缩略图的最小尺寸标准
						if (ConstantUtil.IMG_THUMBNAIL_COMPRESS) {
							// 等比压缩图片
							fileNamePath = ConstantUtil.IMG_PATH + ImgUtil.addSuffixToImage(img.getPath());
							bScaleRatio = ImgUtil.scaleRatio(ConstantUtil.IMG_PATH + img.getPath(), fileNamePath,
									ConstantUtil.IMG_THUMBNAIL_MAX_WIDTH);
						}
						if (bScaleRatio) {
							news.setThumbnail(ImgUtil.addSuffixToImage(img.getNewImgUrl()));
							srcImg.flush();
							break;
						}
						srcImg.flush();
					}
					srcImg.flush();
				} catch (Exception e) {
					log.error(JSON.toJSONString(img), e);
				}
			}
		}

		if (imgList != null && imgList.size() > 0) {
			ImgRepository imgRepository = (ImgRepository) SpringContextUtil.getBean("imgRepository");
			imgRepository.save(imgList);
		}
		
		// 更新news内容
		if (news.getPublishTime() == null) {
			news.setPublishTime(DateUtil.getCurrentDate());
		}
		news.setIsEnabled(true);
		
		newsService.save(news);
		
		if(origHtml != null) {
			// 更新原始页面的内容
			OrigWebpage owPage = origWebpageRepository.findOne(news.getPageId());
			owPage.setContent(origHtml.toString());
			owPage.setInsertTime(DateUtil.getCurrentDate());
			origWebpageRepository.save(owPage);
		}
		
	}

}
